package tutorial.io;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import Util.StdOut;

public class InvoiceIO {

    static final String dataFile = "src/tutorial/io/invoiceRecord.txt";

    static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    static final int[] units = { 12, 8, 13, 29, 50 };
    static final String[] descs = {
        "Java T-shirt",
        "Java Mug",
        "Duke Juggling Dolls",
        "Java Pin",
        "Java Key Chain"
    };
    
    public static void main(String[] args){
        readRecordFile(dataFile);
    }
    
    public void writerRecordFile(String dataFile) {
        DataOutputStream writer = null;
        try {
            writer = new DataOutputStream(new FileOutputStream(dataFile));
            for (int i = 0; i < prices.length; i++) {
                writer.writeDouble(prices[i]);
                writer.writeInt(units[i]);
                writer.writeUTF(descs[i]);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void readRecordFile(String dataFile) {
        DataInputStream reader = null;
        double price = 0;
        int unit = 0;
        String desc = null;
        try {
            reader = new DataInputStream(new FileInputStream(dataFile));
            while (true) {
                price = reader.readDouble();
                unit = reader.readInt();
                desc = reader.readUTF();
                
                System.out.format("Price: %f, Unit count: %d, Desc: %s.%n", price, unit, desc);
            }
        } catch (EOFException e) {
            
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
